export class HistoryManager {
  constructor(maxHistory = 100) {
    this.history = []
    this.index = -1
    this.maxHistory = maxHistory
    this.snapshots = new Map()
    this.initialState = null
  }

  recordState(content, snapshotKey = null) {
    // 记录初始状态
    if (this.index === -1) {
      this.initialState = content
      this.history.push(content)
      this.index = 0
      return
    }

    // 限制历史记录数量
    if (this.history.length >= this.maxHistory) {
      this.history.shift()
      this.index--
    }

    // 跳过重复记录
    if (this.history[this.index] === content) {
      return
    }

    // 截断重做历史
    if (this.index < this.history.length - 1) {
      this.history = this.history.slice(0, this.index + 1)
    }

    this.history.push(content)
    this.index++

    if (snapshotKey) {
      this.snapshots.set(snapshotKey, content)
    }
  }

  undo() {
    if (this.index === 0 && this.initialState !== null) {
      return {
        content: this.initialState,
        canUndo: false,
        canRedo: true
      }
    }

    if (this.index > 0) {
      this.index--
      return {
        content: this.history[this.index],
        canUndo: this.index > 0,
        canRedo: true
      }
    }

    return null
  }

  redo() {
    if (this.index < this.history.length - 1) {
      this.index++
      return {
        content: this.history[this.index],
        canUndo: true,
        canRedo: this.index < this.history.length - 1
      }
    }

    return null
  }

  getSnapshot(key) {
    return this.snapshots.get(key)
  }

  saveSnapshot(key, content) {
    this.snapshots.set(key, content)
  }

  clearHistory() {
    this.history = []
    this.index = -1
    this.initialState = null
  }

  clearSnapshots() {
    this.snapshots.clear()
  }

  get canUndo() {
    return this.index > 0 || (this.index === 0 && this.initialState !== null)
  }

  get canRedo() {
    return this.index < this.history.length - 1
  }

  get currentState() {
    return this.index >= 0 ? this.history[this.index] : this.initialState
  }
}
